package com.example.my_self_view.behavior;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;

public class HeaderBehavior extends CoordinatorLayout.Behavior<View> {

    private int initialHeight = 0; // 头部视图的初始高度

    public HeaderBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout,
                                       @NonNull View child, @NonNull View directTargetChild,
                                       @NonNull View target, int axes, int type) {
        // 监听垂直滚动
        return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
    }

    @Override
    public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout,
                                  @NonNull View child, @NonNull View target,
                                  int dx, int dy, @NonNull int[] consumed, int type) {
        if (initialHeight == 0) {
            initialHeight = child.getHeight(); // 初始化头部视图高度
        }

        // 计算新的高度
        int newHeight = child.getHeight() - dy;

        // 限制高度范围
        if (newHeight < 100) newHeight = 100; // 最小高度
        if (newHeight > initialHeight) newHeight = initialHeight; // 最大高度

        // 设置新的高度
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        params.height = newHeight;
        child.setLayoutParams(params);

        // 消费滚动事件
        consumed[1] = dy;
    }
}